<template>
  <el-row class="form-title">
    <el-col :span="12">
      <span  @click="$router.push('/login')" class="login-text">登录</span>
    </el-col>
    <el-col :span="12">
      <span  @click="$router.push('/register')" >注册</span>
    </el-col>
  </el-row>
  
  <el-col class="form-main"  >
    <el-row class="input-box" type="flex" justify="center">
      <el-col :span="20">
        <el-input
          placeholder="手机号"
          clearable
          prefix-icon="el-icon-mobile-phone"
          v-model="userInfo.phone">
        </el-input>
      </el-col>
    </el-row>
    <el-row class="input-box" type="flex" justify="center">
      <el-col :span="20">
        <el-input
          show-password
          placeholder="密码"
          prefix-icon="el-icon-lock"
          v-model="userInfo.pwd">
        </el-input>
      </el-col>
    </el-row>
    <el-row class="btn-box" type="flex" justify="center">
      <el-col :span="20">
        <el-button  @click="loginVerify" type="primary">登录</el-button>
      </el-col>
    </el-row>
  </el-col>
 
</template>

<script type="text/ecmascript-6">
  import { defineComponent,reactive} from "vue";
  import { useRouter } from "vue-router";
  import { useStore } from 'vuex'
  import { ElMessage } from 'element-plus'
  import { apiLogin } from '../../api/index'
  export default defineComponent({
    name:"Login",
    setup(){

      //操控路由
      const router = useRouter()     
      
      //操控vuex
      const store = useStore()
      const userInfo = reactive({
        phone:"",
        pwd:"",
      })


      //登录
      async function loginVerify(){
        let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
        let { phone,pwd } = userInfo
        if ( !pwd || !phone.trim()){
          ElMessage.error('账号密码不能为空!');
          return
        }
        if ( !reg.test(phone) ){
          ElMessage.error('请输入正确的手机格式!');
          return
        }
        let result = await apiLogin(phone,pwd)
        console.log(result)
        if (result.err_code == 200){
          //将用户数据保存到浏览器和vuex
          window.sessionStorage.setItem('info',JSON.stringify(result.data))
          ElMessage.success({
            message: '登录成功!',
            type: 'success'
          });
          //读取到，则是通过投票页跳转到登录页的，登录成功后让其重新去刚才的投票页
          let voteId = window.localStorage.getItem('v')
          voteId ? router.replace(`/VoteDetail/${voteId}`) : router.replace('/home')
          window.localStorage.removeItem('v')
          // router.replace("/home")
        }else{
          ElMessage.error('账号或密码错误!');
        }
      }
      return {
        userInfo,
        loginVerify
      }
    }
  })
</script>

<style scoped lang="less" >
  @import url("./login_home.less");


</style>
